// pages/show/show.js
import {
  getUser,
  getLottery,
  getWheel
} from '../../api/index'
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app = getApp();
// 设置定时器timer
let trafficWithdrawTimer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 红包弹框
    show1: false,
    show2: false,
    not_open: true,
    animationData: {},
    animationData1: {},
    animationData2: {},

    isShow: true,
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
      phone: null,
      isShow: false
    },
    img: [],
    Lottery: {
      nickName: "",
      phone: "",
      number: null,
    },
    prize: '',
    play: true, //音乐控制，默认是播放
    isShowBoolean: false, // 控制是否能抽奖
    rotateId1: 0, // 当前是第几轮，数字
    rotateId2: '', // 当前是第几轮，汉字
    ismusic: true, // 控制是否展示背景音乐
  },
  // 音乐关
  musicClone() {
    app.bgPause()
    this.setData({
      ismusic: false
    })
  },
  // 音乐开
  musicOpen() {
    app.bgPlay()
    this.setData({
      ismusic: true
    })
  },
  // 抽奖
  async isShow() {
    if (!this.data.isShowBoolean) {
      const digitToChinese = {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        10: '十',
      };
      // 转换成汉字
      if (this.data.rotateId1 === 0) {
        const chineseCharacter = digitToChinese[1];
        wx.showToast({
          title: `第${chineseCharacter}轮抽奖还未开始`,
          icon: 'none'
        });
      } else {
        const chineseCharacter = digitToChinese[this.data.rotateId1 + 1];
        if (this.data.rotateId1 === 10 && !this.data.isShowBoolean) {
          wx.showToast({
            title: `年会抽奖已全部结束`,
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: `第${chineseCharacter}轮抽奖还未开始`,
            icon: 'none'
          });
        }

      }
      console.log(this.data.isShowBoolean);
      console.log(this.data.rotateId1);
    } else {
      // wx.showToast({
      //   title: `抽奖`,
      //   icon: 'none'
      // });
      app.initAudeo2()
      this.setData({
        isShow: false,
        isShowBoolean:false
      })
      const res = await getLottery(this.data.Lottery)
      console.log(res, 'getLottery');
      this.setData({
        prize: res.data.rows[0].prize
      });
      setTimeout(() => {
        wx.showLoading({
          title: '奖品发放中...',
          mask: true
        })
      }, 3000)

      setTimeout(() => {
        app.audioPause()
        this.setData({
          show1: true,
          isShow: true
        }, (() => {
          this.slideIn(0)
        }))
        wx.hideLoading();
      }, 4000);

    }


  },

  closeModal() {
    this.slideIn(1);
    setTimeout(() => {
      this.setData({
        show1: false,
        show2: false
      })
    }, 200);
  },

  slideIn(e) {
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms
      timingFunction: 'linear' //动画的效果 默认值是linear
    })
    this.animation = animation;
    if (e == 0) {
      this.animation.translate('-50%', '-50%').step();
    } else {
      this.animation.translate('-50%', '100%').step();
    }
    this.setData({
      animationData: this.animation.export(),
    })
  },
  // 开启红包
  open() {
    app.initAudeo3()
    this.setData({
      not_open: false
    }, (() => {
      setTimeout(() => {
        this.setData({
          not_open: true,
        })
        this.fadeOut(() => {
          let animation = wx.createAnimation({
            duration: 0,
            timingFunction: 'step-end'
          })
          let animation1 = wx.createAnimation({
            duration: 0,
            timingFunction: 'step-end'
          })
          animation.opacity(1).step();
          animation1.opacity(1).step();
          this.setData({
            show1: false,
            show2: true,
            animationData1: animation.export(),
            animationData2: animation1.export(),
          })
        })
        app.openPause()
      }, 1000);
    }))
    this.setData({
      isShowBoolean: false,
    })
  },

  fadeOut(fun) {
    var animation1 = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease-in-out'
      }),
      animation2 = wx.createAnimation({
        duration: 500,
        timingFunction: 'linear'
      })
    animation1.translateY('-350%').step();
    animation2.translateY('300%').step()
    this.setData({
      animationData1: animation1.export(),
      animationData2: animation2.export(),
    })
    setTimeout(() => {
      fun()
    }, 400);
  },

  // 去中奖记录页
  goRecord() {
    wx.navigateTo({
      url: "/pages/record/record",
    })
    clearInterval(this.getUserTimer);
  },
  // 去游戏页
  goGame() {
    wx.navigateTo({
      url: "/pages/game/game",
    })
    clearInterval(this.getUserTimer);
  },
  // 获取用户信息
  async getUser() {
    const res = await getUser()
    console.log(res, 'getUser');
    this.setData({
      img: res.data.rows,
    })
    // 使用Array.prototype.find方法查找符合条件的元素
    const rowsArray = res.data.rows
const foundUser = rowsArray.find(user => user.nickName === this.data.userInfo.nickName);
// 输出找到的用户信息
console.log(foundUser);
this.setData({
  isShowBoolean: foundUser.isShowBoolean,
})
    console.log(this.data.img);
  },
  // 获取当前是第几轮
  async getWheel() {
    const res = await getWheel()
    console.log(res, 'getWheel');
    if (res.data.rows[0].rotateId > 0) {
      this.setData({
        rotateId1: res.data.rows[0].rotateId,
        'Lottery.number': res.data.rows[0].rotateId,
      })
      if (this.data.isShowBoolean === true) {
          const digitToChinese = {
            1: '一',
            2: '二',
            3: '三',
            4: '四',
            5: '五',
            6: '六',
            7: '七',
            8: '八',
            9: '九',
            10: '十',
          };
          // 转换成汉字
            const chineseCharacter = digitToChinese[res.data.rows[0].rotateId];
            wx.showToast({
              title: `第${chineseCharacter}轮抽奖已开始,请点击抽奖`,
              icon: 'none'
            });
          console.log(this.data.isShowBoolean);
          console.log(res.data.rows[0].rotateId);
        }
    } else {
      this.setData({
        rotateId1: res.data.rows[0].rotateId,
        'Lottery.number': res.data.rows[0].rotateId,
      })
      if (this.data.isShowBoolean === true) {
        const digitToChinese = {
          1: '一',
          2: '二',
          3: '三',
          4: '四',
          5: '五',
          6: '六',
          7: '七',
          8: '八',
          9: '九',
          10: '十',
        };
        // 转换成汉字
          const chineseCharacter = digitToChinese[res.data.rows[0].rotateId];
          wx.showToast({
            title: `第${chineseCharacter}轮抽奖已开始,请点击抽奖`,
            icon: 'none'
          });
        console.log(this.data.isShowBoolean);
        console.log(res.data.rows[0].rotateId);
      }
    }
    console.log(this.data.isShowBoolean);
    console.log(this.data.rotateId1);

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // app.initAudeo()
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res, 'qaz');
        this.setData({
          userInfo: res.data,
          'Lottery.nickName': res.data.nickName,
          'Lottery.phone': res.data.phone,
        });
      }
    })
    // 每隔3秒执行一次 this.getUser()
    // this.getUser();
    // this.getWheel();
    // this.getUserTimer = setInterval(() => {

    // this.getUser();
    // this.getWheel();
    // }, 3000);

  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('生命周期函数--监听页面显示');
    this.setWithdrawTimer(true);
    // 每隔3秒执行一次 this.getUser()
    this.getUser();
    this.getWheel();
    this.getUserTimer = setInterval(() => {

    this.getUser();
    this.getWheel();
    }, 3000);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log(' 生命周期函数--监听页面隐藏');
    this.setWithdrawTimer(false);
    // 在页面隐藏时清除定时器
    clearInterval(this.getUserTimer);
  },
  setWithdrawTimer(flag) {
    let {
      withdrawOpen
    } = this.data
    if (trafficWithdrawTimer) {
      this.clearTrafficWithdrawTimer()
    }
    trafficWithdrawTimer = setTimeout(() => {
      this.setData({
        withdrawOpen: !withdrawOpen
      })
      this.setWithdrawTimer()
    }, flag ? 1000 : 6000)
  },
  clearTrafficWithdrawTimer() {
    if (trafficWithdrawTimer) {
      clearTimeout(trafficWithdrawTimer)
      trafficWithdrawTimer = null
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log(' 生命周期函数--监听页面隐藏');

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }

})